/*
 * @Description: 分货调整明细页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 16:50:24
 */
import React, { useEffect, useState } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  Form,
  MonthPicker,
  notification,
  Select,
  TextField,
  Upload,
} from 'choerodon-ui/pro';
import { ButtonColor } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import intl from 'utils/intl';
import { getAccessToken } from 'utils/utils';
import TerraUploader from '@dji/terra-uploader/lib/IntranetUploader';
import querystring from 'querystring';
import {
  adjustmentFormDS,
  adjustmentTableDS,
  // submitDateSet,
  reqAttachsDS,
  //   approvalDS,
} from '../../stores/distributionAdjustmentDtlDS';

import moment from 'moment';
import { FieldType } from 'choerodon-ui/pro/lib/data-set/enum';
import ProductTable from './component/productTable';
import AttchsList from './component/attchsList';
import formatterCollections from 'utils/intl/formatterCollections';

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
  match: any;
  location: any;
}

const ClassPage: React.FC<propstype> = ({ dispatch, location }) => {
  const tableDS = useDataSet(() => new DataSet(adjustmentTableDS() as DataSetProps));
  const formDS = useDataSet(() => new DataSet(adjustmentFormDS() as DataSetProps));
  // const submitDS = useDataSet(() => new DataSet(submitDateSet() as DataSetProps));
  const reqAttachsDateSet = useDataSet(() => new DataSet(reqAttachsDS() as DataSetProps));

  const [showProductTable, setshowProductTable] = useState(false);
  const [attchsList, setAttchsList] = useState([] as any);

  const { search } = location;
  const queryStr: any = new URLSearchParams(search).get('params');
  const urlParamsObj = JSON.parse(decodeURIComponent(queryStr));

  useEffect(() => {
    if (urlParamsObj && urlParamsObj.id) {
      formDS.setQueryParameter('id', urlParamsObj.id);
      formDS.query().then(res => {
        const adjustmentResults = res.adjustmentResults;
        tableDS.loadData(adjustmentResults);
        setshowProductTable(true);
      });

      // 请求附件
      reqAttachs(urlParamsObj.id);
    } else {
      tableDS.loadData([]);
      formDS.removeAll();
      formDS.create({}, 0);
      setAttchsList([]);
    }
  }, [location.search]);

  // 请求附件
  const reqAttachs = id => {
    reqAttachsDateSet.setQueryParameter('businessId', id);
    reqAttachsDateSet.setQueryParameter('businessType', 'ORDER_ADJUSTMENT');
    reqAttachsDateSet.query().then(res => {
      const attaches = res.content;
      const addEnabledFlagList = attaches.map(item => {
        return {
          ...item,
          enabledFlag: 1,
        };
      });
      setAttchsList(addEnabledFlagList);
    });
  };

  // 附件改造，使用dji terra组件上传附件
  const handleBeforeUpload = file => {
    // 修改文件名 以·截取文件名
    const fileNameList = file.name.split('.');
    // 提出文件类型
    const fileType = fileNameList.pop();

    // 重新组合文件名
    let fileStr = '';
    fileNameList.forEach((item, index) => {
      if (index === 0) {
        fileStr += `${item}`;
      } else {
        fileStr += `.${item}`;
      }
    });

    // 文件名 + 时间 + 文件类型
    const fileName = `${fileStr}-${moment().format('YYYYMMDDHHmmss')}.${fileType}`;
    const directory = 'order';
    // 获取凭证
    const results = new DataSet({
      fields: [
        { name: 'fileId', type: FieldType.string },
        { name: 'uploadToken', type: FieldType.string },
        { name: 'uploadType', type: FieldType.number },
        { name: 'uploadUrl', type: FieldType.string },
        { name: 'headers', type: FieldType.object },
      ],
      queryUrl: `${process.env.API_HOST}/hfle/v3/0/attach/file/in-or-out/token?fileName=${fileName}&directory=${directory}`,
    });

    results.query().then(AuthRes => {
      // 组装数据
      const options = {
        config: {
          ...AuthRes,
          uploadURL: AuthRes.uploadUrl,
        },
        onProgress(percent) {
          console.log(`upload percent ----> ${percent}%`);
        },
        onSuccess() {
          console.log('upload success');
          setAttchsList([
            ...attchsList,
            {
              attachName: fileName,
              realFileKey: AuthRes.fileId,
              enabledFlag: 1,
            },
          ]);
        },
        onError(err) {
          console.log('upload error ----> ', err);
        },
      };

      //const newFile = new File([file], AuthRes.fileName, { type: file.type });
      const newFile = new File([file], fileName, { type: file.type });
      const uploader = new TerraUploader(newFile, options);
      uploader.start();

      file = newFile;
    });
    return false;
  };

  // 保存
  const handleSave = () => {
    handleSubmitorSave('save');
  };

  // 提交
  const handleSubmit = () => {
    handleSubmitorSave('submit');
  };

  const handleSubmitorSave = async type => {
    const validate = await tableDS.validate();
    if (!validate) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.distributionAdjustmentLineRequire`).d('分货调整明细行必填项未填写！！'),
      });
      return;
    }

    formDS.current?.set('type', type);
    const adjustmentResults = handleDjustmentResults();
    formDS.current?.set('adjustmentResults', adjustmentResults);
    formDS.current?.set('attaches', attchsList);
    formDS.submit().then(res => {
      // const id = res.content && res.content.length &&res.content[0].id;
      // console.log(id);
      const id =
        urlParamsObj && urlParamsObj.id ? urlParamsObj.id : res.content && res.content[0].id;

      let paramsObj = {
        id,
        number: Math.random(),
      };
      dispatch(
        routerRedux.push({
          pathname: `/o2om/distribution-adjustment-create`,
          search: querystring.stringify({
            params: encodeURIComponent(JSON.stringify(paramsObj)),
          }),
        })
      );

      // formDS.setQueryParameter('id', id);
      // formDS.query().then(res => {
      //   const adjustmentResults = res.adjustmentResults;
      //   tableDS.loadData(adjustmentResults);
      //   setshowProductTable(true);
      // });
      // // 请求附件
      // reqAttachs(id);
    });
  };

  // 封装行数据
  const handleDjustmentResults = () => {
    let adjustmentResults: any = [];
    const tableList = tableDS.toData();
    if (tableList) {
      const id = formDS.current?.get('id');
      adjustmentResults = tableList.map((item: any) => {
        delete item.outCustomerObj;
        delete item.intoCustomerObj;
        delete item.productCodeObj;
        return {
          ...item,
          adjustmentId: Number(id),
        };
      });
    }
    return adjustmentResults;
  };

  return (
    <PageHeaderWrapper
      title={
        urlParamsObj
          ? intl.get('dji.otc.om.view.menu.editDistributionAdjustmentDtl').d('编辑分货调整明细')
          : intl.get('dji.otc.om.view.menu.createDistributionAdjustmentDtl').d('新建分货调整明细')
      }
      header={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button icon="save" key="save" onClick={() => handleSave()}>
            {intl.get('dji.otc.om.view.button.save').d('保存')}
          </Button>
          <Button
            disabled={!showProductTable}
            key="submit"
            onClick={() => handleSubmit()}
            color={ButtonColor.primary}
          >
            {intl.get(`dji.otc.om.view.button.submit`).d('提交')}
          </Button>
        </div>
      }
    >
      <Form
        dataSet={formDS}
        columns={2}
        header={intl.get('dji.otc.om.view.menu.distributionAdjustment').d('分货调整')}
      >
        <TextField name="adjustmentCode" placeholder={intl.get('dji.otc.om.view.field.generatedByTheSystem').d('系统自动生成')} disabled />
        <TextField name="adjustmentReason" />
        <MonthPicker name="adjustmentMonth" />
        <Select name="adjustmentType" />
        {/* <TextField name="enclosureInfo" /> */}
        <Upload
          name="enclosureInfo"
          action={`${process.env.API_HOST}/v1/cm-contract-attchs/upload/interior`}
          headers={{ Authorization: `bearer ${getAccessToken()}` }}
          multiple={true}
          beforeUpload={handleBeforeUpload}
        />
        <Select name="businessGroup" />
      </Form>
      <AttchsList attchsList={attchsList} setAttchsList={setAttchsList} />
      {showProductTable && <ProductTable tableDS={tableDS} dispatch={dispatch} />}
    </PageHeaderWrapper>
  );
};

export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);
